package fctuc.dei.myTwitter.tests;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import fctuc.dei.myTwitter.client.MyTwitterClient;
import fctuc.dei.myTwitter.client.RunClient;
import fctuc.dei.myTwitter.client.TwitterClientListener;
import fctuc.dei.myTwitter.com.MT;
import fctuc.dei.myTwitter.pojo.Tweet;
import fctuc.dei.myTwitter.pojo.User;

public class SimClient {

	/**
	 * @param args
	 */
	
	public int inicio;
	public int fim;
	public static long[][] times;
	
	public static void main(String[] args){
		if(args.length < 2){
			System.out.println("SimClient <start> <end> <tech>");
			return;
		}
		new SimClient(Integer.parseInt(args[0]), Integer.parseInt(args[1]), args[2]);
	}
	
	public SimClient(int st, int end, String tech){
		this.inicio = st;
		this.fim = end;
		ExecutorService threadPool = Executors.newCachedThreadPool();
		times = new long[fim][3];
		for(int i= inicio; i< fim; i++)
			threadPool.submit(new MyThread(i, threadPool, tech));
		
		threadPool.shutdown();

		try {
			threadPool.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private class MyThread implements Runnable, TwitterClientListener{
		
		private String i;
		private ExecutorService executor;
		private String tech;
		public MyThread(int i, ExecutorService exec, String t){
			this.i = String.valueOf(i);
			this.executor = exec;
			this.tech = t;
		}
		
		
		
		public void run(){
			//true = benchmarkmode on
			MyTwitterClient cl = new MyTwitterClient(this.tech, true);
			cl.addListener(this);
			executor.submit(cl);
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User u = new User();
			u.setUsername(i);
			u.setPassword(i);
			u.setEmail(i);
			cl.currentUser = u; 
			times[Integer.valueOf(i)][1] =  System.currentTimeMillis();
			cl.serverConnection.send(MT.LOGIN, "USER", cl.currentUser, "RECONNECT", "FALSE");
//			for(int k = 0; k<5; k++){
//				Tweet t = new Tweet(String.valueOf(k));
//				t.setUser_id(cl.currentUser.getId());
//				cl.serverConnection.send(MT.TWEET, "TWEET", t);
//			}
			cl.serverConnection.send(MT.LOGOUT, "USER_ID", cl.currentUser.getId());			
		}

		@Override
		public void sessionTerminated() {
			long tempoFinal = System.currentTimeMillis();
			System.err.println(tempoFinal - times[Integer.valueOf(i)][1]);
		}
	}
}
